<template>
  <!--导航栏-->
  <el-affix>
    <TabHead/>
  </el-affix>

  <el-row>
    <!--文章展览区-->
    <el-col :span="20" :offset="2">
        <md-editor v-model="state.form.content" previewOnly="true" class="md"/>
    </el-col>

    <!--打开评论区按钮-->
    <el-col :span="2">
      <el-affix :offset="80" style="margin-right: 20%">
        <el-button
            style="margin-top: 20%;opacity: 0.8"
            @click="comment()"
            circle
            size="large"
        >
          留言区
        </el-button>
      </el-affix>
    </el-col>
  </el-row>

  <!--回到顶部-->
  <el-backtop :right="50" :bottom="100"/>

  <!--评论区-->
  <el-drawer v-model="drawer" title="I am the title" :with-header="false">
    <el-input
        v-model="textarea"
        :rows="3"
        type="textarea"
        placeholder="快来留下你的评论吧"
        size="large"
    />
    <el-button type="primary" style="float: right;margin-top: 10px" @click="commit()">发布</el-button>

    <div style="margin-top: 70px;margin-bottom: -50px" v-for="comments in state.comments" :key="comments.comment_id">
      <el-card class="el-card">
        <div style="font-weight: bold;font-size: 85%">{{comments.username}}:</div>
        <div style="font-weight: bold;margin-left: 40px;font-size: 75%">{{comments.context}}</div>
      </el-card>
    </div>
  </el-drawer>
</template>

<script setup>
import TabHead from "../components/TabHead.vue";
import {reactive, ref} from "vue";
import MdEditor from "md-editor-v3";
import "md-editor-v3/lib/style.css";
import request from "../request.js";
import {useRouter, useRoute} from "vue-router";
import {ElMessage} from "element-plus";


//评论区打开的控制变量
const drawer = ref(false)

//获取传来的id
const route = useRoute();
const ID = route.params.id;

//统一管理变量
const state = reactive({
  form: {
    id: ID,
  },
  comments:[],
})

//加载模块
const load = () => {
  request.get("/article/findAll").then(res => {
    for (const resKey of res) {
      //根据id查找对应文章
      if (resKey.id == ID) {
        state.form.content = resKey.content
      }
    }
  })

  request.get("/comment/findAll").then(res => {
    for (const re of res) {
      state.comments.push(re)
    }
  })
}
load()

//评论判断是否登录
const router = useRouter()
const comment = () => {
  console.log(localStorage)
  if(localStorage.length===0){
    ElMessage({
      message: '请先登录',
      type: 'warning',
    })
    router.push("/Login")
  }else {
    drawer.value=true
  }
}

</script>

<style scoped>
.md {
  height: 100%;
  width: 80%;
  border-radius: 20px;
  margin: 3% auto;
  padding: 5%;
}

.el-button.is-circle {
  border-radius: 50%;
  padding: 50%;
}
</style>
